<script setup>
import { find, forEach, includes, map, merge } from 'lodash-es';
import dayjs from 'dayjs';
import { useRequest, useWatch, useDownload } from '@/hooks';
import { usePickerOption } from '@/views/hooks';
import { dateTypeWatch, runChartWatch } from '@/views/orgMgmt/hooks.js';
import { contractType, arrowClassMap } from '@/constants.js';
import { basicTitle, basicLineXAxis, basicLineYAxis, basicLineLegend } from '@/components/chart/options/baseOptions.js';
import { getEngTypesByCode, getAreaList, getBuildingByArea, entEngChartData } from '@/api/index.js';
import { TableList } from '@/components/MainComponents.js';
import CECharts from '@/components/chart/CECharts.vue';

const rangeType = ref({
  d: {
    type: 'daterange',
    fmt: 'yyyy-MM-dd',
    default: [dayjs().subtract(30, 'day').format('YYYY-MM-DD'), dayjs().subtract(1, 'day').format('YYYY-MM-DD')],
    pickerOptions: usePickerOption('d'),
  },
  m: {
    type: 'monthrange',
    fmt: 'yyyy-MM',
    default: [dayjs().subtract(6, 'month').format('YYYY-MM'), dayjs().subtract(1, 'month').format('YYYY-MM')],
    pickerOptions: usePickerOption('m'),
  },
  y: { type: 'year', fmt: 'yyyy', default: [dayjs().subtract(2, 'year').format('YYYY'), dayjs().format('YYYY')] },
});
const queryForm = ref(null);
const cascader = ref(null);
const contractName = ref(null);
const cascaderProps = ref({
  emitPath: true,
  checkStrictly: true,
  label: 'areaName',
  value: 'areaName',
});

const cascaderChange = bool => {
  if (!bool) {
    insParams.value.areaName = cascader.value.join('/');
    runIns(insParams.value);
  }
};

const selEngType = ref(null);
const textStyle = {
  color: '#f5f5f5',
  fontWeight: 'normal',
  fontSize: 16,
  lineHeight: 18,
};
const commonOpts = {
  title: [
    merge({}, basicTitle, {
      text: '能耗趋势',
      top: 10,
      textStyle,
    }),
    merge({}, basicTitle, {
      text: '收益趋势',
      textStyle,
      top: '53%',
    }),
  ],
  tooltip: {
    formatter: params => {
      if (Array.isArray(params) && params.length > 0) {
        let str = `<div class="u-mb5">${params[0].axisValue}</div>`;
        forEach(params, e => {
          let seriesName = e.seriesName;
          let value = e.value[e.dimensionNames[e.encode.y]] ?? '--';
          if (
            e.dimensionNames[e.encode.y] === 'energyEarningsConservationCost' &&
            chartParams.value.contractType === 'SHARE'
          ) {
            value = `${value} (占比: ${e.value.energyEarningsConservationRatio ?? '-'}%)`;
          }
          if (includes(seriesName, '环比') || includes(seriesName, '同比')) {
            const sign = Math.sign(value);
            value = value !== '--' ? `${value}% <i class="${arrowClassMap.get(sign)} u-fs14"></i>` : `${value}%`;
          }
          str += `<ul class="u-df-spb u-mb5"><li>${e.marker}${seriesName}</li><li class="u-ml30">${value}</li></ul>`;
        });
        return str;
      }
      return '';
    },
  },
  axisPointer: {
    link: { xAxisIndex: 'all' },
  },
  color: ['#26d5d5', '#4992ff', '#eda422', '#f53019', '#5afe5d', '#f58819', '#fe5a5a', '#d5d526'],
  dataZoom: null,
};
const lineExtraOpts1 = ref(merge({}, commonOpts));
const initValue = {
  inId: null,
  contractType: null,
  dateType: 'd',
  energyType: 0,
  projectType: 'TG',
  dateStart: rangeType.value.d.default[0],
  dateEnd: rangeType.value.d.default[1],
};
const chartParams = ref({
  inId: null,
  contractType: null,
  dateType: 'd',
  energyType: 0,
  projectType: 'TG',
  isUnit: 'yes',
  dateStart: rangeType.value.d.default[0],
  dateEnd: rangeType.value.d.default[1],
});
const [tableData, loading, runChart] = useRequest(entEngChartData, {
  defaultParams: [chartParams.value],
  manual: true,
  onSuccess: res => {
    setChartOpt();
    map(getDimensionsByType()[chartParams.value.contractType], (v, i) => {
      lineExtraOpts1.value.dataset[i].dimensions = v;
      lineExtraOpts1.value.dataset[i].source = res.data;
    });
    setSeriesByType();
    lineExtraOpts1.value.yAxis[0].name = `单位：${selEngType.value.energyUnit ?? ''}`;
  },
});

const getDimensionsByType = () => {
  return {
    CONVENTION: [
      [
        'energyValueDate',
        { name: 'energyBasisValue', displayName: '基准能耗' },
        { name: 'energyConsumeValue', displayName: '实际能耗' },
        { name: 'energyConservationValue', displayName: '节能量' },
        { name: 'energyConservationValueRatio', displayName: '节能率' },
      ],
      [
        'energyValueDate',
        { name: 'energyBasisCost', displayName: '基准费用' },
        { name: 'energyConsumeCost', displayName: '实际费用' },
        { name: 'energyEarningsConservationCost', displayName: '项目收益' },
      ],
    ],
    SHARE: [
      [
        'energyValueDate',
        { name: 'energyBasisValue', displayName: '基准能耗' },
        { name: 'energyConsumeValue', displayName: '实际能耗' },
        { name: 'energyConsumeValueRatio', displayName: '实际能耗环比' },
        { name: 'energyConservationValue', displayName: '节能量' },
        { name: 'energyConservationValueRatio', displayName: '节能率' },
      ],
      [
        'energyValueDate',
        { name: 'energyBasisCost', displayName: '基准费用' },
        { name: 'energyConsumeCost', displayName: '实际费用' },
        { name: 'energyConservationCost', displayName: '节能总收益' },
      ],
      [
        'energyValueDate',
        { name: 'energyConservationCost', displayName: '项目节能总收益' },
        { name: 'energyEarningsConservationCost', displayName: '综能项目总收益' },
        { name: 'energyConservationCostRatio', displayName: '综能项目收益环比' },
      ],
    ],
    ENSURE: [
      [
        'energyValueDate',
        { name: 'energyBasisValue', displayName: '基准能耗' },
        { name: 'energyConsumeValue', displayName: '实际能耗' },
        { name: 'energyConsumeValueRatio', displayName: '实际能耗环比' },
        { name: 'energyConservationValue', displayName: '节能量' },
        { name: 'energyConservationValueRatio', displayName: '节能率' },
      ],
      [
        'energyValueDate',
        { name: 'energyGuaranteeConservationValue', displayName: '保证节能量' },
        { name: 'energyConservationValue', displayName: '实际节能量' },
        { name: 'energyConservationValueGap', displayName: '节能量差值' },
      ],
      [
        'energyValueDate',
        { name: 'energyBasisCost', displayName: '标准服务费' },
        { name: 'energyEarningsConservationCost', displayName: '实际项目收益' },
        { name: 'energyConservationCostRatio', displayName: '项目收益环比' },
      ],
    ],
  };
};
const setSeriesByType = () => {
  let seriesSet = [];
  if (chartParams.value.contractType === 'CONVENTION') {
    lineExtraOpts1.value.legend[0].data = ['基准能耗', '实际能耗'];
    lineExtraOpts1.value.legend[1].data = ['基准费用', '实际费用'];
    for (let i = 0; i < 2; i++) {
      const item = lineExtraOpts1.value.dataset[i];
      const arr = Array.from({ length: item.dimensions.length - 1 }, (_, idx) => {
        if (idx === 0) {
          const obj = {
            type: 'line',
            smooth: true,
            showSymbol: false,
            lineStyle: { type: 'dashed' },
          };
          if (i === 0) {
            obj.datasetIndex = 0;
            obj.xAxisIndex = 0;
            obj.yAxisIndex = 0;
          } else {
            obj.datasetIndex = 1;
            obj.xAxisIndex = 2;
            obj.yAxisIndex = 2;
          }
          return obj;
        } else if (idx === 1) {
          const obj = {
            type: 'bar',
            showSymbol: false,
            smooth: true,
            barWidth: 12,
          };
          if (i === 0) {
            obj.datasetIndex = 0;
            obj.xAxisIndex = 0;
            obj.yAxisIndex = 0;
          } else {
            obj.datasetIndex = 1;
            obj.xAxisIndex = 2;
            obj.yAxisIndex = 2;
          }
          return obj;
        } else {
          const obj = {
            type: 'line',
            symbol: 'none',
            lineStyle: { opacity: 0 },
          };
          if (i === 0) {
            obj.datasetIndex = 0;
            obj.xAxisIndex = 0;
            obj.yAxisIndex = 1;
          } else {
            obj.datasetIndex = 1;
            obj.xAxisIndex = 2;
            obj.yAxisIndex = 3;
          }
          return obj;
        }
      });
      seriesSet = seriesSet.concat(arr);
    }
  }
  if (chartParams.value.contractType === 'SHARE') {
    lineExtraOpts1.value.legend[0].data = ['基准能耗', '实际能耗', '实际能耗环比'];
    lineExtraOpts1.value.legend[1].data = ['基准费用', '实际费用'];
    lineExtraOpts1.value.legend[2].data = ['项目节能总收益', '综能项目总收益', '综能项目收益环比'];
    for (let i = 0; i < 3; i++) {
      const item = lineExtraOpts1.value.dataset[i];
      const arr = Array.from({ length: item.dimensions.length - 1 }, (_, idx) => {
        if (idx === 0) {
          const obj =
            i < 2
              ? {
                  type: 'line',
                  smooth: true,
                  showSymbol: false,
                  lineStyle: { type: 'dashed' },
                }
              : {
                  type: 'bar',
                  barWidth: 20,
                };
          if (i === 0) {
            obj.datasetIndex = 0;
            obj.xAxisIndex = 0;
            obj.yAxisIndex = 0;
          } else if (i === 1) {
            obj.datasetIndex = 1;
            obj.xAxisIndex = 2;
            obj.yAxisIndex = 2;
          } else {
            obj.datasetIndex = 2;
            obj.xAxisIndex = 4;
            obj.yAxisIndex = 4;
          }
          return obj;
        } else if (idx === 1) {
          const obj = {
            type: 'bar',
            showSymbol: false,
            smooth: true,
            barWidth: 12,
          };
          if (i === 0) {
            obj.datasetIndex = 0;
            obj.xAxisIndex = 0;
            obj.yAxisIndex = 0;
          } else if (i === 1) {
            obj.datasetIndex = 1;
            obj.xAxisIndex = 2;
            obj.yAxisIndex = 2;
          } else {
            obj.barWidth = 20;
            obj.barGap = '-100%';
            obj.datasetIndex = 2;
            obj.xAxisIndex = 4;
            obj.yAxisIndex = 4;
          }
          return obj;
        } else if (idx === 2) {
          const obj =
            i === 1
              ? {
                  type: 'line',
                  symbol: 'none',
                  lineStyle: { opacity: 0 },
                }
              : {
                  type: 'line',
                  smooth: true,
                  showSymbol: false,
                };
          if (i === 0) {
            obj.datasetIndex = 0;
            obj.xAxisIndex = 0;
            obj.yAxisIndex = 1;
          } else if (i === 1) {
            obj.datasetIndex = 1;
            obj.xAxisIndex = 2;
            obj.yAxisIndex = 3;
          } else {
            obj.datasetIndex = 2;
            obj.xAxisIndex = 4;
            obj.yAxisIndex = 5;
          }
          return obj;
        } else {
          const obj = {
            type: 'line',
            symbol: 'none',
            lineStyle: { opacity: 0 },
          };
          if (i === 0) {
            obj.datasetIndex = 0;
            obj.xAxisIndex = 0;
            obj.yAxisIndex = 1;
          } else if (i === 1) {
            obj.datasetIndex = 1;
            obj.xAxisIndex = 2;
            obj.yAxisIndex = 3;
          } else {
            obj.datasetIndex = 2;
            obj.xAxisIndex = 4;
            obj.yAxisIndex = 5;
          }
          return obj;
        }
      });
      seriesSet = seriesSet.concat(arr);
    }
  }
  if (chartParams.value.contractType === 'ENSURE') {
    lineExtraOpts1.value.legend[0].data = ['基准能耗', '实际能耗', '实际能耗环比'];
    lineExtraOpts1.value.legend[1].data = ['保证节能量', '实际节能量'];
    lineExtraOpts1.value.legend[2].data = ['标准服务费', '实际项目收益', '项目收益环比'];
    for (let i = 0; i < 3; i++) {
      const item = lineExtraOpts1.value.dataset[i];
      const arr = Array.from({ length: item.dimensions.length - 1 }, (_, idx) => {
        if (idx === 0) {
          const obj = {
            type: 'line',
            smooth: true,
            showSymbol: false,
            lineStyle: { type: 'dashed' },
          };
          if (i === 0) {
            obj.datasetIndex = 0;
            obj.xAxisIndex = 0;
            obj.yAxisIndex = 0;
          } else if (i === 1) {
            obj.datasetIndex = 1;
            obj.xAxisIndex = 2;
            obj.yAxisIndex = 2;
          } else {
            obj.datasetIndex = 2;
            obj.xAxisIndex = 4;
            obj.yAxisIndex = 4;
          }
          return obj;
        } else if (idx === 1) {
          const obj = {
            type: 'bar',
            showSymbol: false,
            smooth: true,
            barWidth: 12,
          };
          if (i === 0) {
            obj.datasetIndex = 0;
            obj.xAxisIndex = 0;
            obj.yAxisIndex = 0;
          } else if (i === 1) {
            obj.datasetIndex = 1;
            obj.xAxisIndex = 2;
            obj.yAxisIndex = 2;
          } else {
            obj.datasetIndex = 2;
            obj.xAxisIndex = 4;
            obj.yAxisIndex = 4;
          }
          return obj;
        } else if (idx === 2) {
          const obj =
            i === 1
              ? {
                  type: 'line',
                  symbol: 'none',
                  lineStyle: { opacity: 0 },
                }
              : {
                  type: 'line',
                  smooth: true,
                  showSymbol: false,
                };
          if (i === 0) {
            obj.datasetIndex = 0;
            obj.xAxisIndex = 0;
            obj.yAxisIndex = 1;
          } else if (i === 1) {
            obj.datasetIndex = 1;
            obj.xAxisIndex = 2;
            obj.yAxisIndex = 3;
          } else {
            obj.datasetIndex = 2;
            obj.xAxisIndex = 4;
            obj.yAxisIndex = 5;
          }
          return obj;
        } else {
          const obj = {
            type: 'line',
            symbol: 'none',
            lineStyle: { opacity: 0 },
          };
          if (i === 0) {
            obj.datasetIndex = 0;
            obj.xAxisIndex = 0;
            obj.yAxisIndex = 1;
          } else if (i === 1) {
            obj.datasetIndex = 1;
            obj.xAxisIndex = 2;
            obj.yAxisIndex = 3;
          } else {
            obj.datasetIndex = 2;
            obj.xAxisIndex = 4;
            obj.yAxisIndex = 5;
          }
          return obj;
        }
      });
      seriesSet = seriesSet.concat(arr);
    }
  }
  lineExtraOpts1.value.series = seriesSet;
};
const setChartOpt = () => {
  if (chartParams.value.contractType === 'CONVENTION') {
    const cObj = {
      title: [{}, { top: '53%' }],
      grid: [
        { bottom: 20, top: 80, left: '5%', right: 5, height: '27%' },
        { bottom: 10, top: '65%', left: '5%', right: 5, height: '27%' },
      ],
      legend: [
        merge({}, basicLineLegend, {
          data: [],
          x: 'center',
          y: 40,
        }),
        merge({}, basicLineLegend, {
          data: [],
          x: 'center',
          y: '53%',
        }),
      ],
      dataset: Array.from({ length: 2 }, () => ({ dimensions: [], source: [] })),
    };
    const axisObj = {
      xAxis: [
        merge({}, basicLineXAxis, { gridIndex: 0 }),
        { gridIndex: 0, show: false },
        merge({}, basicLineXAxis, { gridIndex: 1 }),
        { gridIndex: 1, show: false },
      ],
      yAxis: [
        merge({}, basicLineYAxis, {
          name: '单位：tce',
          nameTextStyle: { fontSize: 12 },
          gridIndex: 0,
        }),
        merge({}, basicLineYAxis, {
          name: '单位：%',
          nameTextStyle: { fontSize: 12, align: 'right' },
          gridIndex: 0,
        }),
        merge({}, basicLineYAxis, {
          name: '单位：元',
          nameTextStyle: { fontSize: 12 },
          gridIndex: 1,
        }),
        merge({}, basicLineYAxis, {
          name: '单位：%',
          nameTextStyle: { fontSize: 12, align: 'right' },
          gridIndex: 1,
        }),
      ],
    };
    lineExtraOpts1.value = merge({}, lineExtraOpts1.value, cObj);
    lineExtraOpts1.value.xAxis = axisObj.xAxis;
    lineExtraOpts1.value.yAxis = axisObj.yAxis;
  }
  if (includes(['SHARE', 'ENSURE'], chartParams.value.contractType)) {
    const identicalOpt = {
      dataset: Array.from({ length: 3 }, () => ({ dimensions: [], source: [] })),
      xAxis: [
        merge({}, basicLineXAxis, { gridIndex: 0 }),
        { gridIndex: 0, show: false },
        merge({}, basicLineXAxis, { gridIndex: 1 }),
        { gridIndex: 1, show: false },
        merge({}, basicLineXAxis, { gridIndex: 2 }),
        { gridIndex: 2, show: false },
      ],
      yAxis: [
        merge({}, basicLineYAxis, {
          name: '单位：tce',
          nameTextStyle: { fontSize: 12 },
          gridIndex: 0,
        }),
        merge({}, basicLineYAxis, {
          name: '单位：%',
          nameTextStyle: { fontSize: 12, align: 'right' },
          gridIndex: 0,
        }),
        merge({}, basicLineYAxis, {
          name: '单位：元',
          nameTextStyle: { fontSize: 12 },
          gridIndex: 1,
        }),
        merge({}, basicLineYAxis, {
          name: '单位：%',
          nameTextStyle: { fontSize: 12, align: 'right' },
          gridIndex: 1,
        }),
        merge({}, basicLineYAxis, {
          name: '单位：元',
          nameTextStyle: { fontSize: 12 },
          gridIndex: 2,
        }),
        merge({}, basicLineYAxis, {
          name: '单位：%',
          nameTextStyle: { fontSize: 12, align: 'right' },
          gridIndex: 2,
        }),
      ],
    };
    const getExtraOpt = () => {
      const legendArr = [
        merge({}, basicLineLegend, { data: [], x: 'center' }),
        merge({}, basicLineLegend, { data: [], x: 'center' }),
        merge({}, basicLineLegend, { data: [], x: 'center' }),
      ];
      const sObj = {
        grid: [
          { bottom: 20, top: 80, left: '5%', right: 5, height: '19%' },
          { bottom: 20, top: '47%', left: '5%', right: 5, height: '19%' },
          { bottom: 20, top: '77%', left: '5%', right: 5, height: '19%' },
        ],
        title: [{}, { top: '38%' }],
        legend: merge([], legendArr, [{ y: 40 }, { y: '40%' }, { y: '72%' }]),
      };
      const eObj = {
        grid: [
          { bottom: 20, top: 80, left: '5%', right: 5, height: '19%' },
          { bottom: 20, top: '43%', left: '5%', right: 5, height: '19%' },
          { bottom: 20, top: '77%', left: '5%', right: 5, height: '19%' },
        ],
        title: [{}, { top: '68%' }],
        legend: merge([], legendArr, [{ y: 40 }, { y: '38%' }, { y: '72%' }]),
      };

      return chartParams.value.contractType === 'SHARE' ? sObj : eObj;
    };

    lineExtraOpts1.value = merge({}, lineExtraOpts1.value, { ...identicalOpt, ...getExtraOpt() });
  }
};
runChartWatch(chartParams.value, runChart);

const columnObj = ref({
  CONVENTION: {
    index: true,
    columnData: [
      {
        text: true,
        prop: 'energyValueDate',
        label: '统计时间',
        width: 100,
      },
      {
        text: true,
        prop: 'energyType',
        label: '能源类型',
        width: 100,
      },

      {
        prop: 'energyBasisValue',
        label: '基准能耗',
        text: true,
      },
      {
        prop: 'energyConsumeValue',
        label: '实际能耗',
        text: true,
      },
      {
        prop: 'energyConservationValue',
        label: '节能量',
        text: true,
      },
      {
        prop: 'energyConservationValueRatio',
        label: '节能率(%)',
        text: true,
      },
      {
        prop: 'energyBasisCost',
        label: '基准费用(元)',
        text: true,
      },
      {
        prop: 'energyConsumeCost',
        label: '实际费用(元)',
        text: true,
      },
      {
        prop: 'energyEarningsConservationCost',
        label: '项目收益(元)',
        text: true,
      },
    ],
  },
  SHARE: {
    index: true,
    columnData: [
      {
        text: true,
        prop: 'energyValueDate',
        label: '统计时间',
        width: 100,
      },
      {
        text: true,
        prop: 'energyType',
        label: '能源类型',
        width: 100,
      },
      {
        prop: 'energyBasisValue',
        label: '基准能耗',
        text: true,
      },
      {
        prop: 'energyConsumeValue',
        label: '实际能耗',
        text: true,
      },
      {
        prop: 'energyConsumeValueRatio',
        label: '实际能耗环比(%)',
        width: 140,
        text: true,
      },
      {
        prop: 'energyConservationValue',
        label: '节能量',
        text: true,
      },
      {
        prop: 'energyConservationValueRatio',
        label: '节能率(%)',
        text: true,
      },
      {
        prop: 'energyBasisCost',
        label: '基准费用(元)',
        text: true,
      },
      {
        prop: 'energyConsumeCost',
        label: '实际费用(元)',
        text: true,
      },
      {
        prop: 'energyConservationCost',
        label: '节能总收益(元)',
        text: true,
      },
      {
        prop: 'energyEarningsConservationRatio',
        label: '综能收益占比(%)',
        width: 140,
        text: true,
      },
      {
        prop: 'energyEarningsConservationCost',
        label: '综能项目总收益(元)',
        text: true,
      },
      {
        prop: 'energyConservationCostRatio',
        label: '综能项目收益环比',
        width: 140,
        text: true,
      },
    ],
  },
  ENSURE: {
    index: true,
    columnData: [
      {
        text: true,
        prop: 'energyValueDate',
        label: '统计时间',
        width: 100,
      },
      {
        text: true,
        prop: 'energyType',
        label: '能源类型',
        width: 100,
      },
      {
        prop: 'energyBasisValue',
        label: '基准能耗',
        text: true,
      },
      {
        prop: 'energyConsumeValue',
        label: '实际能耗',
        text: true,
      },
      {
        prop: 'energyConsumeValueRatio',
        label: '实际能耗环比(%)',
        text: true,
      },
      {
        prop: 'energyConservationValue',
        label: '节能量',
        text: true,
      },
      {
        prop: 'energyConservationValueRatio',
        label: '节能率(%)',
        text: true,
      },
      {
        prop: 'energyGuaranteeConservationValue',
        label: '保证节能量/节能率(%)',
        text: true,
      },
      {
        prop: 'energyConservationValueGap',
        label: '节能量/率差值',
        text: true,
      },
      {
        prop: 'energyBasisCost',
        label: '标准服务费(元)',
        text: true,
      },
      {
        prop: 'energyEarningsConservationCost',
        label: '实际项目收益(元)',
        text: true,
      },
      {
        prop: 'energyConservationCostRatio',
        label: '项目收益环比(%)',
        text: true,
      },
    ],
  },
});

const handleInId = val => {
  chartParams.value.contractType = val?.contractTypeCode ?? null;
  etParams.value.enterpriseCode = val?.enterpriseCode ?? null;
  contractName.value = find(contractType, v => v.code === val?.contractTypeCode)?.name ?? '-';
};
const changeType = item => {
  selEngType.value = item;
};

const handleExport = () => {
  useDownload('/energyservice/NewOverviewController/getByDateEnergyResultExcel', chartParams.value);
};
const handleQuery = () => {};
const resetQuery = async () => {
  await runArea({});
  chartParams.value = merge(chartParams.value, initValue);
};

const insParams = ref({
  isStage: '1',
  areaName: null,
  projectType: 'TG',
});
const [areaList, , runArea] = useRequest(getAreaList, {
  defaultParams: [{}],
  onSuccess: res => {
    cascader.value = res.data?.[0]?.areaName ?? null;
    insParams.value.areaName = cascader.value;
    runIns(insParams.value);
  },
});
const [institutionList, , runIns] = useRequest(getBuildingByArea, {
  defaultParams: [{}],
  manual: true,
  onSuccess: res => {
    const initIns = find(res.data, v => includes(['JCOPERATION', 'OPERATION'], v.entrustStage));
    etParams.value.enterpriseCode = initIns?.enterpriseCode ?? null;
    chartParams.value.contractType = initIns?.contractTypeCode ?? null;
    chartParams.value.inId = initIns?.enterpriseCode ?? null;
  },
});
const etParams = ref({
  enterpriseCode: null,
  projectType: 'TG',
  allType: true,
});
const [engTypeList, , runEngType] = useRequest(getEngTypesByCode, {
  manual: true,
  onSuccess: res => {
    chartParams.value.energyType = res.data?.[0]?.id ?? null;
    selEngType.value = res.data?.[0] ?? null;
  },
});

useWatch(etParams, n => runEngType(n), { deep: true });

const dateRange1 = ref(rangeType.value.d.default);
const yearRange1 = ref({ sYear: null, eYear: null });
const disabledDateStart1 = ref({
  disabledDate: time => {
    if (yearRange1.value.eYear) {
      return (
        dayjs(time) > dayjs(yearRange1.value.eYear) || dayjs(time) < dayjs(yearRange1.value.eYear).subtract(2, 'year')
      );
    }
  },
});
const disabledDate1 = ref({
  disabledDate: time => {
    return dayjs(time) < dayjs(yearRange1.value.sYear) || dayjs(time) > dayjs(yearRange1.value.sYear).add(2, 'year');
  },
});
const handleDaterange1 = val => {
  chartParams.value.dateStart = val?.[0] ?? null;
  chartParams.value.dateEnd = val?.[1] ?? null;
};
const handleYearrange1 = () => {
  chartParams.value.dateStart = yearRange1.value.sYear;
  chartParams.value.dateEnd = yearRange1.value.eYear;
};
dateTypeWatch(chartParams, dateRange1, yearRange1, rangeType);
</script>

<template>
  <div class="app-container">
    <el-form ref="queryForm" inline class="u-base-fg u-p20 u-mb20">
      <el-form-item label="行政区划">
        <el-cascader
          v-model="cascader"
          :props="cascaderProps"
          :options="areaList"
          placeholder="请选择行政区划"
          size="small"
          clearable
          @visible-change="cascaderChange"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="机构名称">
        <el-select v-model="chartParams.inId" placeholder="请输入机构名称" filterable size="small">
          <el-option
            v-for="(val, index) in institutionList"
            :key="`${val.enterpriseCode}-${index}`"
            :label="val.enterpriseName"
            :value="val.enterpriseCode"
            @click.native="handleInId(val)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="机构托管类型">
        {{ contractName ?? find(contractType, v => v.code === chartParams.contractType)?.name }}
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button type="primary" size="small" plain @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="u-base-fg u-p20 insHeight">
      <el-form :model="chartParams" :inline="true" class="u-df-ed insHeight-form">
        <el-form-item prop="energyType" class="u-mr10">
          <el-select v-model="chartParams.energyType" placeholder="" size="mini" class="u-mr10">
            <el-option
              v-for="item in engTypeList"
              :key="item.id"
              :label="item.energyName + '能耗'"
              :value="item.id"
              @click.native="changeType(item)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="rangeType[chartParams.dateType].type !== 'year'">
          <el-date-picker
            v-model="dateRange1"
            :type="rangeType[chartParams.dateType].type ?? 'daterange'"
            :key="rangeType[chartParams.dateType].type ?? 'daterange'"
            :value-format="rangeType[chartParams.dateType].fmt ?? 'yyyy-MM-dd'"
            :picker-options="rangeType[chartParams.dateType].pickerOptions"
            :clearable="false"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="mini"
            align="left"
            class="u-mr10"
            style="width: 240px"
            @change="handleDaterange1"
          />
        </el-form-item>
        <el-form-item v-else>
          <el-date-picker
            v-model="yearRange1.sYear"
            :picker-options="disabledDateStart1"
            :clearable="false"
            type="year"
            value-format="yyyy"
            placeholder="开始年份"
            size="mini"
            style="width: 115px"
            class="u-mr5"
            @change="handleYearrange1"
          />
          <el-date-picker
            v-model="yearRange1.eYear"
            :picker-options="disabledDate1"
            :clearable="false"
            type="year"
            value-format="yyyy"
            placeholder="结束年份"
            size="mini"
            class="u-mr10"
            style="width: 115px"
            @change="handleYearrange1"
          />
        </el-form-item>
        <el-form-item prop="dateType" style="margin-right: 0 !important">
          <el-radio-group v-model="chartParams.dateType" size="mini">
            <el-radio-button label="d">日</el-radio-button>
            <el-radio-button label="m">月</el-radio-button>
            <el-radio-button label="y">年</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <CECharts
        v-if="chartParams.contractType === 'CONVENTION'"
        v-loading="loading"
        :options="lineExtraOpts1"
        type="line"
        style="height: 500px"
      />
      <CECharts v-else v-loading="loading" :options="lineExtraOpts1" type="line" style="height: 650px" />
      <div class="u-df-ed u-mt20 u-mb20">
        <el-button type="primary" size="small" plain @click="handleExport">导出报表</el-button>
      </div>
      <TableList
        v-show="chartParams.contractType === 'CONVENTION'"
        v-loading="loading"
        :tableData="tableData ?? []"
        :columObj="columnObj['CONVENTION']"
        :height="500"
      ></TableList>
      <TableList
        v-show="chartParams.contractType === 'SHARE'"
        v-loading="loading"
        :tableData="tableData ?? []"
        :columObj="columnObj['SHARE']"
        :height="500"
      ></TableList>
      <TableList
        v-show="chartParams.contractType === 'ENSURE'"
        v-loading="loading"
        :tableData="tableData ?? []"
        :columObj="columnObj['ENSURE']"
        :height="500"
      ></TableList>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.insHeight {
  height: calc(100% - 100px);
  position: relative;
  overflow-y: auto;
  &-form {
    position: absolute;
    top: 20px;
    right: 20px;
    z-index: 999;
  }
}
:deep(.el-form-item) {
  margin-bottom: 0;
  .el-form-item__content {
    height: 40px;
    line-height: 40px;
  }
}
</style>
